package com.nine.shop.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nine.shop.common.ServerResponse;
import com.nine.shop.mapper.OrderMapper;
import com.nine.shop.model.*;
import com.nine.shop.utils.JsonUtil;
import com.nine.shop.vo.OrderVo;
import com.nine.shop.vo.PageVo;
import com.sun.org.apache.xpath.internal.operations.And;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.constraints.Pattern;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author Shawsw
 * Create on 2019/8/17
 */
@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> {

    @Resource
    private UserService userService;

    @Resource
    private AddressService addressService;

    @Resource
    private GoodsService goodsService;


    /**
     * @param current 页码
     * @param size    每页大小
     * @Description:查询所有Order
     * @return:
     * @Author: Shawsw
     * @Date: 2019/8/27 12:34
     */
    public ServerResponse findAllOrder(Integer current, Integer size) {
        IPage<Order> orderIPage = baseMapper.selectPage(new Page<Order>(current, size), new QueryWrapper<Order>().isNotNull("userId"));
        List<Order> orderList = orderIPage.getRecords();
        List<OrderVo> newOrderList = new ArrayList<OrderVo>();
        int new_userId;
        for (Order order : orderList) {
            new_userId = order.getUserId();
            Address address = addressService.selectByUserId(new_userId);
            String this_address=address.getAddress();
            if (this_address==null)
            {
                this_address="未设置地址" ;
            }
            OrderVo orderVo = new OrderVo(order,this_address);
            newOrderList.add(orderVo);
        }
        PageVo<OrderVo> orderVoPageVo = new PageVo<OrderVo>(orderIPage.getCurrent(), orderIPage.getTotal(), orderIPage.getSize(), orderIPage.getPages(), newOrderList);
        return ServerResponse.createBySuccess(orderVoPageVo);
    }


    /**
     * 修改Order通过OrderId
     *
     * @Description: updateOrder
     * @Param: [order]
     * @Param: [order]
     * @return: int
     * @Author: Shawsw
     * @Date: 2019/8/27 12:35
     */
    public int updateOrder(Order order) {
        return baseMapper.updateById(order);
    }

    /**
     * 删除Order通过OrderId
     *
     * @Description: delectOrderById
     * @Param: [orderId]
     * @Param: [orderId]
     * @return: com.nine.shop.common.ServerResponse
     * @Author: Shawsw
     * @Date: 2019/8/27 12:36
     */
    public ServerResponse delectOrderById(Integer orderId) {

        if (orderId == null) {
            return ServerResponse.createByErrorMsg("orderId ERROR");
        } else {
            int flag;
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", orderId);
            flag = baseMapper.delete(queryWrapper);
            if (flag == 0) {
                return ServerResponse.createByErrorMsg("删除失败");
            } else {
                return ServerResponse.createBySuccessMsg("删除成功");

            }

        }
    }

    /**
     * 增加Order
     */
    public int insertOrder(Order order) {
        return baseMapper.insert(order);
    }


    /**
     * @Description:
     * @Param:
     * @Param:
     * @return:
     * @Author: Shawsw
     * @Date: 2019/8/27 13:48
     */
    public IPage<Order> findByUserIdPage(Integer current, Integer size, Integer userId) {
        return baseMapper.selectPage(new Page<>(current, size), new QueryWrapper<Order>().eq("userId", userId));
    }


    /**
     * 分页查看全部订单
     * zhangxinfei
     */
    public ServerResponse searchOrderByUserId(int limit, int page, int userId) {
        //分页查询订单信息
        IPage iPage = pageMaps(new Page<>(page, limit), new QueryWrapper<Order>().eq("userId", userId));
        List<Map> list = iPage.getRecords();
        for (int i = 0; i < list.size(); i++) {
            Map map = list.get(i);
            //获取商品id
            int goodsId = (int) map.get("goodsId");
            //获取商品信息
            Goods goods = goodsService.getById(goodsId);
            map.put("goods", goods);
        }
        if (list.size() > 0) {
            PageVo pageVo = new PageVo();
            pageVo.setCurrent(iPage.getCurrent());
            pageVo.setData(list);
            pageVo.setSize(iPage.getSize());
            pageVo.setTotal(iPage.getTotal());
            pageVo.setPages(iPage.getPages());
            return ServerResponse.createBySuccess(pageVo);
        }
        return ServerResponse.createByErrorMsg("查看失败!");
    }


    /**
     * @Description 提交订单
     * @Param [order]
     * @Return int
     * @Author wangcong
     * @Date 2019/8/25
     * @Time 15:54
     */
    public int insertToOrede(Order order) {
        return baseMapper.insert(order);
    }


    /**
     * @Description: 根据
     * @Param: userId:登录用户ID
     * @Param:
     * @return: ServerResponse
     * @Author: Shawsw
     * @Date: 2019/8/27 11:09
     */
    public ServerResponse payForOrder(Integer userId, String payPsd, String orderlist, Double allcost) {

        User user = userService.selectUserByUserId(userId);
        if (user == null) {
            return ServerResponse.createByErrorMsg("未找到用户");
        }
        String true_payPsd = user.getPayPsd();

        if (payPsd == null) {
            return ServerResponse.createByErrorMsg("未找到登录用户的支付密码");
        }
        if (true_payPsd.equals(payPsd)) {
            int Flag = 0;
            List<Order> orderList = JsonUtil.str2obj(orderlist, List.class);
            if (orderList.isEmpty()) {
                return ServerResponse.createByErrorMsg("未提交任何商品");
            }
            for (Order order : orderList) {
                Integer orderId = order.getId();
                Order order1 = baseMapper.selectOne(new QueryWrapper<Order>().
                        and(i -> i.eq("userId", userId).eq("id", orderId)));
                order1.setStatus(1);
                int flag = baseMapper.update(order1, new QueryWrapper<Order>().
                        and(i -> i.eq("userId", userId).eq("id", orderId)));
                if (flag == 1) {
                    Flag++;
                }
            }
            if (Flag == orderList.size())//是否全部order发货更新完毕
            {
                //全部order发货更新完毕
                //扣除余额
                Double userBalance = user.getBalance() - allcost;
                user.setBalance(userBalance);
                userService.updateUserinfo(user);
                return ServerResponse.createBySuccessMsg("订单支付成功");
            } else {
                return ServerResponse.createByErrorMsg("订单为支付失败，数据库失败");
            }
        } else {
            return ServerResponse.createByErrorMsg("支付密码错误");
        }

    }


    /**
     * @Description:
     * @Param:
     * @Param:
     * @return:
     * @Author: Shawsw
     * @Date: 2019/8/27 13:59
     */
    public ServerResponse sendOrder(Integer orderId) {
        Order order = baseMapper.selectOne(new QueryWrapper<Order>().eq("id", orderId));
        if (order == null) {
            return ServerResponse.createByErrorMsg("未找到该订单");
        } else {
            order.setStatus(2);
            baseMapper.updateById(order);
            return ServerResponse.createBySuccessMsg("发货成功");
        }


    }

}
